//vuex权限模块
import { constantRoutes, asnycRoutes, errorRoutes } from '@/router'
const state = {
    //最终结果 渲染到左侧
    routes: [],
    addRoutes: [],  //计算好的动态路由
    isGetUserInfo: false, //是否获取用户信息 判断token是否正确
}

// 计算单个路由是否有权限
/**
 * @param {any} route
 * @param {string} role
 * @description
 * @returns {boolean}
 */

//计算动态路由有权限函数
const hasPermission = (route, role) => {
    //如果当前路由 有roles字段
    if (route.meta?.roles) {
      // ['super','vip']  'super'
      return route.meta.roles.includes(role)
    } else {
      return true
    }
  }

//计算动态路由权限函数
const filterAsyncRoutes = (routes, role) => {
    let temp = []
    routes.forEach(route => {
      if (hasPermission(route, role)) {
        //如果有儿子 儿子也需要计算
        if (route.children?.length) {
          route.children = filterAsyncRoutes(route.children, role)
        }
        temp.push(route)
      }
    })
  
    return temp
  }
// console.log(filterAsyncRoutes(asnycRoutes,'normal'));

const mutations = {
    ADD_ROUTES(state, routes) {
      //把静态路由 和 计算好的动态路由 合并给左侧菜单使用
      state.routes = [...constantRoutes, ...routes]
    },
    //设置用户信息状态
    SET_USERINFO_STATE(state, flag) {
      state.isGetUserInfo = flag
    },
  }
  
  const actions = {
    //生成动态路由函数
    generateRoutes({commit}, role) {
      return new Promise(resolve => {
        //筛选出可使用的动态路由
        let accessRoutes = filterAsyncRoutes(asnycRoutes, role)
  
        //把accessRoutes 存进vuex
        commit('ADD_ROUTES', accessRoutes)
  
        //把筛选好的动态路由 和 错误路由 抛出去 给router.addRoutes用
        resolve([...accessRoutes, ...errorRoutes])
      })
    },
  }

export default {
    namespaced: true,
    state,
    mutations,
    actions,
}